﻿using Orchard;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using Orchard.Settings;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Users.Models;
using PmpNetwork.Models;
using PmpNetwork.ViewModels;
using Orchard.UI.Navigation;
using PmpNetwork.Extensions;
namespace PmpNetwork.Services
{
    public class WikiArticleService: IWikiArticleService
    {
        private readonly IOrchardServices _orchardServices;
        public WikiArticleService(IOrchardServices orchardServices)
        {
            this._orchardServices = orchardServices;
        }

        public IList<WikiArticlePart> Search(WikiSearchViewModel search, PaginationInfo paging)
        {
            var predicate = PredicateBuilder.True<WikiArticlePartRecord>();

            var expression = search.Expression ?? String.Empty;
            if (!expression.EndsWith("%")) expression += "%";
            if (!expression.StartsWith("%")) expression = "%" + expression;
            
            predicate.And(w => w.Name.Contains(expression));

            paging.TotalRecords = _orchardServices.ContentManager.Query<WikiArticlePart, WikiArticlePartRecord>()
                .Where(predicate)
                .Count();

            return _orchardServices.ContentManager.Query<WikiArticlePart, WikiArticlePartRecord>()
                .Where(predicate)
                .OrderByDescending(w => w.CreatedDate)
                .Slice(paging.StartIndex, paging.PageSize.Value)
                .ToList();
        }

        public WikiArticlePart Get(int id)
        {
            return _orchardServices.ContentManager.Get<WikiArticlePart>(id);
        }
        public WikiArticlePart Get(string name)
        {
            return _orchardServices.ContentManager.Query<WikiArticlePart, WikiArticlePartRecord>()
                .Where(w => w.NameOnUrl == name)
                .Slice(1)
                .FirstOrDefault();
        }
    }
}